<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class TokenMiddleware implements MiddlewareInterface
{
    protected ContainerInterface $container;

    protected RequestInterface $request;

    protected HttpResponse $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response  = $response;
        $this->request   = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 1、获取token
        $headerArr = $this->request->getHeader('token');
        if (empty($headerArr) || empty($headerArr[0])) {
            return $this->response->json(
                [
                    'code' => -1001,
                    'data' => [
                        'error' => 'Token is Fail',
                    ],
                ]
            );
        }
        $token = $headerArr[0];

        // 2、通过token判断当前用户
        $user_info = $this->getUserByToken($token);
        if (empty($user_info)) {
            return $this->response->json(
                [
                    'code' => -1002,
                    'data' => [
                        'error' => 'user is none',
                    ],
                ]
            );
        }

        // 3、设定用户信息
        $this->request->user_info = $user_info;
        return $handler->handle($request);
    }

    /**
     * (用户表)获取用户信息
     * @param string $token
     * @return array
     */
    private function getUserByToken(string $token): array
    {
        return match ($token) {
            'aaa111' => [
                'user_id' => 1,
                'user_name' => 'admin',
            ],
            'bbb222' => [
                'user_id' => 2,
                'user_name' => 'zhangsan',
            ],
            'ccc333' => [
                'user_id' => 3,
                'user_name' => 'lisi',
            ],
            default => [],
        };
    }
}
